package com.wzf.greattruth.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

/**
 * 
 * @author wuzhengfei
 *
 */

public class ClientConnectCompletionHandler implements CompletionHandler<Void, AsyncClientHandler> {

	@Override
	public void completed(Void result, AsyncClientHandler attachment) {
		byte[] req = "timestemp".getBytes();
		ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
		writeBuffer.put(req);
		writeBuffer.flip();

		ClientWriteCompletionHandler writeCompletionHandler = new ClientWriteCompletionHandler(
				attachment.asynSocketChannel, attachment.latch);
		attachment.asynSocketChannel.write(writeBuffer, writeBuffer, writeCompletionHandler);
	}

	@Override
	public void failed(Throwable exc, AsyncClientHandler attachment) {
		exc.printStackTrace();
		try {
			attachment.asynSocketChannel.close();
			attachment.latch.countDown();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
